<template>
  <div>
    <el-container>
      <el-header class="titleBar">
        轮播图管理
      </el-header>

      <el-main class="mainContent">
        <el-card>
          <!-- 按钮操作列表 -->
          <el-row :gutter="10" class="btnControl">
            <el-col :span="22"><div class="box_title"></div></el-col>
            <el-col :span="2">
              <el-button type="success" size="mini"  @click="addDialogVisible = true"
                ><i
                  class="el-icon-circle-plus-outline"
                  @click="addDialogVisible = true"
                ></i>
                添加</el-button
              ></el-col
            >
          </el-row>
          <!-- 表单数据 -->
          <el-table
            :data="chartlist"
            border
            style="width: 100%"
            :header-cell-style="{
              textAlign: 'center',
              background: '#ededed',
              color: '#333',
              fontWeight: '500',
            }"
            :cell-style="{ textAlign: 'center' }"
          >
          <el-table-column label="id" prop="id"></el-table-column>
            <el-table-column label="图片" prop="image">
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.image"
                  style="width:100px;height:60px"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>

            <el-table-column
              label="轮播图位置"
              prop="position"
            ></el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-row :gutter="20" class="opBtn">
                  <el-col :span="10" class="etBtn">
                    <!-- 编辑 -->
                    <el-button
                      type="text"
                      size="small"
                      @click="showEditDialog(scope.row)"
                      >编辑</el-button
                    >
                  </el-col>
                  <!-- 删除 -->
                  <el-col :span="10">
                    <el-button
                      type="text"
                      size="small"
                      class="deleteBtn"
                      @click="removeId(scope.row)"
                      >删除</el-button
                    >
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.pagenum"
            :page-sizes="[3, 5, 10, 15]"
            :page-size="pagination.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          >
          </el-pagination>
        </el-card>
      </el-main>
    </el-container>

    <!-- 添加轮播图 -->
    <el-dialog
      title="添加轮播图"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="addDialogClosed">
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item prop="file" label="图片：">
          <div class="pictitle">
            <b>上传头像</b>(请上传文件大小不超过10MB的正方形图片)
          </div>
          <el-upload
            class="avatar-uploader"
            ref="upload"
            action="#"
            :data="addForm"
            :show-file-list="false"
            :multiple="false"
            :auto-upload="false"
            :on-change="imgSaveToUrl"
          >
            <img v-if="this.addForm.image" :src="this.addForm.image" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑轮播图 -->
    <el-dialog
      title="修改轮播图信息"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editDialogClosed"
      >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
        @close="editDialogClosed"
      >
        <el-form-item label="路径：" prop="position">
          <el-select v-model="editForm.position" placeholder="请选择路径">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="file" label="图片：">
          <el-upload
            class="avatar-uploader"
            ref="upload"
            action="#"
            :data="editForm"
            :show-file-list="false"
            :multiple="false"
            :auto-upload="false"
            :on-change="imgSaveToUrl">
              <img
                v-if="this.editForm.image"
                :src="this.editForm.image"
                class="avatar"/>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="editChartInfo">确 定</el-button>

      </span>
    </el-dialog>
    
  </div>
</template>

<script>
export default {
  data() {
    return {
      // select死数据
      options: [
        {
          value: "选项1",
          label: "尾板",
        },
        {
          value: "选项2",
          label: "车厢",
        },
      ],
      value: "",
      //
      //
      chartInfo: {
        total: 2,
        list: "",
      },
      pagination: {
        pagenum: 1,
        pagesize: 5,
        total: 7,
      },
      chartlist: [],
      addDialogVisible: false,
      addForm: {
        id: "",
        image: "",
        position: "",
        
      },
       file: "",
      addFormRules: {
        position: [{ required: true, message: "请输入数值", trigger: "blur" }],
      },
     
      options: [
        { value: "01", label: "01" },
        { value: "02", label: "02" },
        { value: "03", label: "03" },
        { value: "04", label: "04" },
        { value: "05", label: "05" },
      ],
      // 控制修改对话框的显示与隐藏
     editDialogVisible: false,
      // 查询用户信息对象
      editForm: {
        id: "",
        image: "",
        position: "",  
      },
      // 修改表单的校验规则对象
      editFormRules: {
        image: [{ required: true, message: "请输入数值", trigger: "blur" }],

      },
      editlist: [],
    };
  },
  methods: {
    // 获取数据
    async getChartList() {
      const res = await this.http.get("/chart/selectPage", this.pagination);
      this.chartlist = res.list;
      this.pagination.total = res.total;
      console.log(res);
    },
    //  监听pagesize的改变
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.pagination.pagesize = newSize;
      this.getChartList();
    },
    // 监听 页码值 改变
    handleCurrentChange(newPage) {
      this.pagination.pagenum = newPage;
      this.getChartList();
    },
    // 添加轮播图
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    onSubmit() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        //  发送网路请求
        const { res } = await this.http.post("/chart/add", this.addForm);
        console.log(res);

        if (status.code !== 200) {
           this.$message.error("添加行为失败");
        }
        this.$message.success("添加行为成功！");
        this.addDialogVisible = false;
        this.getChartList();
      });
    },
    // 删除轮播图
    async removeId(row) {
      console.log(row);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
      .catch((error) => error);
      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const res = await this.http.post("/chart/delete", row.id);
      console.log(res);
      this.getChartList();
    },
    //图片上传
    async imgSaveToUrl(event) {
      if (this.beforeUploadPicture(event.raw)) {
        var formData = new FormData();
        console.log(formData);
        formData.append("file", event.raw);
        this.http.upload("/chart/upload", formData).then((res) => {
          if (status.code !== 200) {
            this.addForm.image = res.data;
            // this.editForm.image = this.addForm.image
            this.editForm.image = res.data;
            console.log(res.data);
            console.log(this.addForm);
         this.$message.success("上传成功");
          }
        });
      }
    },
    // 图片上传之前
    beforeUploadPicture(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG 或者 PNG 格式!");
      }
      if (isJPG && isPNG) {
        if (!isLt10M) {
          this.$message.error("上传头像图片大小不能超过 10MB!");
        }
      }

      return (isJPG || isPNG) && isLt10M;
    },
    // 编辑
     async showEditDialog(row){
        const res = await this.http.post("/chart/update", this.editForm);
        
        this.editForm= row
        this.editDialogVisible = true
        console.log(row)
    },
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改用户信息并提交
    editChartInfo(){
          this.$refs.editFormRef.validate(async valid => {
          // console.log(valid);
          if(!valid) return
          // 发起请求获取
          const res = await this.http.post('/chart/update',this.editForm,{
            position:this.editForm.position,
            // image:this.addForm.image
            image:this.editForm.image
          })

          if(status.code !== 200){
            this.$message.error('更新轮播图失败！')
          }
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据
          this.getChartList()
          // 提示修改成功
          this.$message.success('更新轮播图成功!')
          console.log(res);
        }) 
    }
   

  },
  created() {
    this.getChartList();
  },
};
</script>

<style scoped>
.header_title {
  font-size: 22px;
  margin-bottom: 0px;
  font-weight: 400;
  color: #999999;
}
.bgk {
  background: pink;
}
</style>
